package com.ihr360.expr;

import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.AbstractBinaryOperator;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprEvaluatable;
import com.ihr360.expr.core.ExprNumber;
import com.ihr360.expr.core.ExprType;

public class ExprStringConcat extends AbstractBinaryOperator {
    public ExprStringConcat(Expr lhs, Expr rhs) {
        super(ExprType.StringConcat, lhs, rhs);
    }

    @Override
    public Expr evaluate(IEvaluationContext context) throws ExprException {
        Expr l = lhs;
        if (l instanceof ExprEvaluatable){
            l = ((ExprEvaluatable) lhs).evaluate(context);
        }
        if (l instanceof ExprNumber){
            l = new ExprString(l.toString());
        }
        Expr r = rhs;
        if (r instanceof ExprEvaluatable){
            r = ((ExprEvaluatable) rhs).evaluate(context);
        }
        if (r instanceof ExprNumber){
            r = new ExprString(r.toString());
        }
        if (l.type.equals(ExprType.String) && r.type.equals(ExprType.String)) {
            return new ExprString(((ExprString) l).str + ((ExprString) r).str);
        }

        throw new ExprException("Unexpected arguments for string concatenation");
    }

    @Override
    public String toString() {
        return lhs + "&" + rhs;
    }
}
